package se.grp03.fmtuner.scheduler.message;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;

import se.grp03.fmtuner.scheduler.SchedulerManager;
import se.grp03.fmtuner.scheduler.io.UdpConstants;

public class TuneMessage implements MessageInterface {

	private SchedulerManager sm;
	private String message;

	public TuneMessage(String msg) {
		this.message = msg;
		sm = SchedulerManager.getInstance();
	}

	@Override
	public String process() {
		try {	
			// Parse frequency from message.
			StringTokenizer st = new StringTokenizer(message);
			String frequency = st.nextToken();
			
			// Parse date from message.
			// -------------> Sample date string "Thu Sep 28 20:29:30 JST 2000";
		    DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
		    StringBuilder sb = new StringBuilder();
			sb.append(st.nextToken());
			while(st.hasMoreTokens()) {
				sb.append(" ");
				sb.append(st.nextToken());
			}
			Date time = df.parse(sb.toString());
			
			System.out.println("** FREQ: " + frequency);		// DEBUG
			//System.out.println("** SB:   " + sb.toString());	// DEBUG
			System.out.println("** DATE: " + time.toString());	// DEBUG
			
			// Finalize job details with Scheduler, and report results.
			sm.scheduleTuneJob(frequency, time);
			return UdpConstants.OK;
		} 
		catch (ParseException e) {
			System.err.println("** ERROR: " + e);
			System.err.println("Valid Date Format:  Tue Apr 26 23:05:30 EDT 2014");
		}
		catch (NoSuchElementException e) { System.err.println("** ERROR: " + e); }
		
		/*StringBuilder sb = new StringBuilder();
		sb.append(frequency);
		sb.append(" ");
		sb.append(time);
		System.out.println("TuneMessage Processing msg: " + sb.toString());
		return sb.toString();*/
		return UdpConstants.ERROR;
	}
}